package com.salesmanager.core.business.oauth2.dao;

import com.salesmanager.core.base.QueryResult;
import com.salesmanager.core.base.QueryResultJPAImpl;
import com.salesmanager.core.business.generic.dao.SalesManagerJpaDaoSupport;
import com.salesmanager.core.business.oauth2.model.OauthClientDetails;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.List;

@Repository("oauthClientDetailsDao")
public class OauthClientDetailsDaoImpl extends SalesManagerJpaDaoSupport implements OauthClientDetailsDao {

    @Override
    public OauthClientDetails findOauthClientDetails(String clientId) {
        if(clientId==null){
            return null;
        }
         String sql = " select * from oauth_client_details where  client_id = :clientId ";
        Query query = super.getEntityManager().createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        query.setParameter("clientId",clientId);
        List list=query.getResultList();
        if (list.size()>=0) {
            QueryResult row = new QueryResultJPAImpl(list);
            while (row.next()){
                OauthClientDetails oauthClientDetails = new OauthClientDetails();
                oauthClientDetails.clientId( row.getString("client_id"));
                oauthClientDetails.resourceIds( row.getString("resource_ids"));
                oauthClientDetails.clientSecret( row.getString("client_secret"));
                oauthClientDetails.scope(row.getString("scope"));
                oauthClientDetails.authorizedGrantTypes(row.getString("authorized_grant_types"));
                oauthClientDetails.webServerRedirectUri( row.getString("web_server_redirect_uri"));
                oauthClientDetails.authorities(row.getString("authorities"));
                oauthClientDetails.accessTokenValidity( row.getString("access_token_validity"));
                oauthClientDetails.refreshTokenValidity(row.getString("refresh_token_validity"));
                oauthClientDetails.additionalInformation( row.getString("additional_information"));
                oauthClientDetails.createTime( row.getString("create_time"));
                oauthClientDetails.trusted( row.getString("trusted"));
                oauthClientDetails.autoApprove( row.getString("autoapprove"));
                row.close();
                return oauthClientDetails;
            }
        return  null;
        }else{
            return null;
        }

    }

}
